<template>
  <div class="app-container">
    <div class="search-form">
      <el-input
        v-model="listQuery.orderNo"
        clearable
        placeholder="请输入订单号"
        style="width: 200px;"
        class="filter-item"
        size="small"
        @keyup.enter.native="submit"
      />
       <el-input
        v-model="listQuery.verificationCode"
        clearable
        placeholder="请输入核销码"
        style="width: 200px;"
        class="filter-item"
        size="small"
        @keyup.enter.native="submit"
      />
      <el-input
        v-model="listQuery.paymentPhone"
        clearable
        placeholder="请输入电话号码"
        size="small"
        style="width: 140px;"
        class="filter-item"
        @keyup.enter.native="submit"
      />
      <label class="form-key" style="margin-left: 20px;">订单日期：</label>
      <el-date-picker
        v-model="listQuery.startTime"
        clearable
        size="small"
        style="width:200px;"
        type="datetime"
        placeholder="选择日期"
      />
      <el-date-picker
        v-model="listQuery.endTime"
        clearable
        size="small"
        style="width:200px;"
        type="datetime"
        placeholder="选择日期"
      />
      <span>支付状态：</span>
      <el-select
        v-model="listQuery.paymentStatus"
        size="small"
        placeholder="请选择"
        clearable
        class="filter-item"
        style="width: 120px"
      >
        <el-option label="全部" value />
        <el-option label="待支付" value=1 />
        <el-option label="已支付" value=2 />
        <el-option label="已退款" value=3 />
      </el-select>
      <span style="margin-left:10px">订单状态：</span>
      <el-select
        v-model="listQuery.reverseStatus"
        size="small"
        placeholder="请选择"
        clearable
        class="filter-item"
        style="width: 120px"
        @change="handleSelectStatus"
      >
        <el-option label="全部" value />
        <el-option label="待核销" value=1 />
        <el-option label="已核销" value=2 />
        <el-option label="已提现" value=3 />
      </el-select>
      <el-checkbox
        v-model="listQuery.isShowNote"
        class="filter-item"
        style="margin-left:15px;"
      >查看已备注的订单</el-checkbox>
      <el-button
        v-waves
        size="mini"
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        style="margin-left: 20px;"
        @click="submit"
      >查询</el-button>
      <el-button
        v-waves
        size="mini"
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-upload2"
        @click="handleExcelDownload"
      >导出Excel</el-button>
      <el-button
        v-waves
        size="mini"
        class="filter-item"
        type="primary"
        icon="el-icon-download"
        @click="importOrderDialog=true"
      >导入订单</el-button>
    </div>

    <el-table
      :key="tableKey"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      height="655"
      max-height="660"
      :element-loading-text="global.loadingStr"
      :header-cell-style="{background:global.mainColor}"
    >
      <el-table-column label="订单号" align="center" width="200px">
        <template slot-scope="{row}">
          <span>{{ row.orderNo }}</span>
        </template>
      </el-table-column>
      <el-table-column label="学生姓名" align="center" width="100px">
        <template slot-scope="{row}">
          <span>{{ row.childName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="联系电话" align="center" width="150px">
        <template slot-scope="{row}">
          <span>{{ row.paymentPhone }}</span>
        </template>
      </el-table-column>
      <el-table-column label="课程/套餐名称" align="center" width="200px">
        <template slot-scope="{row}">
          <span>{{ row.setMealName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="套餐金额" align="center" width="90px">
        <template slot-scope="{row}">
          <span>{{ row.commodityAmount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="实付金额" align="center" width="90px">
        <template slot-scope="{row}">
          <span>{{ row.paidInAmount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="机构优惠金额" align="center" width="120px">
        <template slot-scope="{row}">
          <span>{{ row.businessDiscountAmount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="平台优惠金额" align="center" width="120px">
        <template slot-scope="{row}">
          <span>{{ row.platformDiscountAmount }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="佣金" align="center" width="90px">
        <template>
          <span></span>
        </template>
      </el-table-column> -->
        <el-table-column label="购买时间" align="center" width="200px">
        <template slot-scope="{row}">
          <span>{{ row.paymentTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" align="center">
        <template slot-scope="{row}">
          <span>{{ row.reverseStatus | orderStatus }}</span>
        </template>
      </el-table-column>
      <el-table-column label="支付状态" align="center">
        <template slot-scope="{row}">
          <span>{{ row.paymentStatus | orderType }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单来源" align="center" width="80px">
        <template slot-scope="{row}">
          <span>{{ row.orderSource | orderSource }}</span>
        </template>
      </el-table-column>
      <el-table-column label="买家备注" align="center">
        <template slot-scope="{row}">
          <span>{{ row.buyerNotes }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center">
        <template slot-scope="{row}">
          <span>{{ row.sellerNotes }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="300px">
        <template slot-scope="{row}">
          <el-button v-if="row.activityId" type="primary" size="mini" @click="handleCheckGroupList(row)">查看团员</el-button>
          <el-button type="primary" size="mini" @click="handleEditSeller(row)">编辑备注</el-button>
          <!-- <el-button type="success" size="mini" @click="handleUpdate(row)">
            排课申请
          </el-button>-->
          <el-button type="success" size="mini" @click="handleOrderInfo(row)">订单详情</el-button>
          <el-button v-if="row.reverseStatus!==2" type="warning" size="mini" @click="handleWriteOff(row)">核销</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.currentPage"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    />
    <!-- 编辑备注 -->
    <el-dialog
      title="编辑备注"
      :visible.sync="sellerNotesDialog"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      @close="sellerNotes=''"
      width="500px"
    >
      <el-input v-model.trim="sellerNotes" placeholder="请输入备注"></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="sellerNotesDialog = false">取 消</el-button>
        <el-button type="primary" @click="confimEditSeller">确 定</el-button>
      </span>
    </el-dialog>
     <!-- 核销订单 -->
    <el-dialog
      title="核销订单"
      :visible.sync="writeOffDialog"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      @close="writeOffOrder=''"
      width="500px"
    >
      <el-input v-model="writeOffOrder" placeholder="请输入核销码"></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="writeOffDialog = false">取 消</el-button>
        <el-button type="primary" @click="confimWriteOff">核 销</el-button>
      </span>
    </el-dialog>
    <!-- 导入订单 -->
    <el-dialog
      title="导入订单（Excel）"
      :visible.sync="importOrderDialog"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      @close="fileList=[]"
      width="500px"
    >
      <el-row style="margin-bottom:10px">
        <el-upload
          style="margin-right:10px"
          action="#"
          accept=".xlsx, .xls"
          :limit="2"
          list-type
          :on-change="removeLastFile"
          :http-request="handleOnsuccess"
          :on-exceed="handleOnExceed"
          :file-list="fileList"
        >
          <el-button size="small">导入文件</el-button>
        </el-upload>
      </el-row>
      <el-row>
        <el-col>
          <i class="el-icon-warning" /> 请先
          <el-button type="text">
            <a
              href="http://ossdev0.oss-cn-shenzhen.aliyuncs.com/%E8%AE%A2%E5%8D%95%E6%A8%A1%E6%9D%BF.xlsx"
            >下载模板</a>
          </el-button>，按格式填写，再导入！
        </el-col>
      </el-row>
      <el-row>
        <span style="color:red;font-size:12px">
          <i class="el-icon-warning"></i> 请勿修改模板文件名，避免导入失败
        </span>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="importOrderDialog = false">取 消</el-button>
        <el-button type="primary" @click="confimImportOrder">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="拼团成员名单"
      :visible.sync="groupDialog"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      @close="groupData=[]"
      >
      <el-table :data="groupData" border style="width: 100%">
        <el-table-column  prop="date" label="用户头像">
          <template slot-scope="{row}">
            <img :src="row.avatar" style="width: 80px;">
          </template>
        </el-table-column>
        <el-table-column  prop="userName" label="用户名"></el-table-column>
        <el-table-column  prop="date" label="是否团长">
          <template slot-scope="{row}">
            <span v-if="row.isLeader === 1">团长</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="{row}">
          <span>
            <el-button type="primary" @click="handleGroup(row)">查看成员</el-button>
          </span>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="closeGroupCheck">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="成员名单"
      :visible.sync="membersDialog"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      @close="membersData=[]"
    >
      <el-table :data="membersData" border style="width: 100%">
        <el-table-column  prop="date" label="用户头像">
          <template slot-scope="{row}">
            <img :src="row.avatar" style="width: 80px;">
          </template>
        </el-table-column>
        <el-table-column  prop="userName" label="用户名"></el-table-column>
        <el-table-column  prop="date" label="是否团长">
          <template slot-scope="{row}">
            <span>{{row.isLeader===1?'团长':'普通成员'}}</span>
          </template>
        </el-table-column>
      </el-table>
      <p>团长：1</p>
      <p>成员：{{ memberLength }}</p>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="closeMemberCheck">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { urlEncode } from '@/utils'
import { orderList, updateById, writeOffOrder,groupMembers,groupDetail } from '@/api/order'
import axios from 'axios'
export default {
  name: 'OrderList',
  directives: { waves },
  components: { Pagination },
  data() {
    return {
      currentRow: '',
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      sellerNotesDialog: false,
      writeOffDialog: false,
      writeOffOrder: '',
      sellerNotes: '',
      orderDetailDialog: true,
      listQuery: {
        currentPage: 1,
        pageSize: 10,
        orderNo: '',
        verificationCode: '',
        paymentPhone: '',
        startTime: '',
        endTime: '',
        businessId: this.$store.getters.businessId,
        paymentStatus: '',
        reverseStatus: '',
        isShowNote: false
      },
      importOrderDialog: false, // 导入订单
      importFileUrl: '',
      fileList: [],
      totalData:[],
      groupData:[],
      membersData:[],
      groupDialog:false,
      membersDialog:false,
      memberLength:0
    }
  },
  filters: {
    orderStatus(val) {
      switch (val) {
        case 1:
          return '待核销'

        case 2:
          return '已核销'

        case 3:
          return '已提现'

        case 4:
          return '提现审核中'

        case 5:
          return '提现通过'
      }
    },
    orderSource(val) {
      switch (val) {
        case 1:
          return '线上'

        case 2:
          return '线下'
      }
    }
  },
  created() {},
  mounted() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      var data = new Map()
      for (const key of Object.keys(this.listQuery)) {
        data[key] = this.listQuery[key] == null ? '' : this.listQuery[key]
      }
      data.startTime =
        data.startTime !== ''
          ? this.listQuery.startTime.getTime()
          : data.startTime
      data.endTime =
        data.endTime !== '' ? this.listQuery.endTime.getTime() : data.endTime
      orderList(data).then(response => {
        this.list = response.data.records
        this.total = response.data.total
        this.listLoading = false
      })
    },
    submit() {
      if(!this.listQuery.orderNo){
        TDAPP.onEvent('订单号搜索订单')
      }
      this.listQuery.currentPage = 1
      this.getList()
    },
    handleSelectStatus(){
      switch (this.listQuery.reverseStatus){
        case 1:
          TDAPP.onEvent('订单待核销查询')
          break;
          case 2:
          TDAPP.onEvent('订单已核销查询')
          break;
          case 3:
          TDAPP.onEvent('订单已提现查询')
          default:
      }
    },
    handleEditSeller(row) {
      this.currentRow = row
      this.sellerNotes = row.sellerNotes
      this.sellerNotesDialog = true
    },
    handleOrderInfo(row) {
      this.$router.push({
        path: '/financial/order/detail',
        query: {
          id: row.id
        }
      })
    },
    handleWriteOff(row) {
      this.currentRow = row
      const { orderNo, verificationCode } = this.currentRow
      this.writeOffOrder = orderNo + verificationCode
      this.writeOffDialog = true
    },
    confimWriteOff() {
      if (this.writeOffOrder === '') {
        this.$message({
          message: '请输入核销码',
          type: 'error'
        })
        return
      }
      writeOffOrder(
        {
          'verificationCode': this.writeOffOrder,
          'orderId': this.currentRow.id
        }
      ).then(res => {
        this.$message({
          message: '核销成功',
          type: 'success'
        })
        this.writeOffDialog = false
        this.getList()
      })
    },
    confimEditSeller(row) {
      updateById({
        id: this.currentRow.id,
        sellerNotes: this.sellerNotes
      }).then(res => {
        this.sellerNotesDialog = false
        this.getList()
        this.$message({
          message: '编辑成功',
          type: 'success'
        })
      })
    },
    handleOnsuccess(response, file, fileList) {
      this.importFileUrl = response.file
    },
    // 移除上一个文件
    removeLastFile(files, fileList) {
      if (fileList.length > 1) {
        this.importFileUrl = fileList.splice(0, 1)
      }
    },
    handleOnExceed(file, fileList) {
      this.$message({
        message: '当前限制上传 1 个文件，请先删除上一个文件，再上传',
        type: 'error',
        duration: 5000
      })
    },
    // 导入订单
    confimImportOrder() {
      if (!this.importFileUrl) {
        return this.$message({
          message: '请先导入文件',
          type: 'error'
        })
      }
      const uploadApi = '/jbl-order/api/merchant/v1/order/import'
      const param = new FormData()
      param.append('file', this.importFileUrl)
      param.append('businessId', this.$store.getters.businessId)
      const config = {
        headers: {
          'Content-Type': 'multipart/form-data',
          'Access-Control-Allow-Origin': '*'
        }
        // responseType: 'blob'
      }
      axios
        .post(process.env.VUE_APP_BASE_API + uploadApi.substr(1), param, config)
        .then(response => {
          // console.log('提交成功')
          // console.log(response)
          if (!response.data.success) {
            this.$message({
              message: '导入失败,请按格式填写',
              type: 'error'
            })
          } else {
            if (response.data.successCount === response.data.total) {
              TDAPP.onEvent('导入订单')
              this.$message({ message: '操作成功', type: 'success' })
              this.importOrderDialog = false
              this.getList()
            } else {
              this.$message({
                message: '操作失败,请查看下载文件',
                type: 'error',
                duration: 0,
                showClose: true
              })
              window.location.href =
                process.env.VUE_APP_BASE_API +
                '/jbl-order/api/merchant/v1/order/import?fileName=' +
                response.data.errorsFile
            }
          }
        })
    },
    handleExcelDownload() {
      TDAPP.onEvent('导出订单')
      var data = new Map()
      for (const key of Object.keys(this.listQuery)) {
        data[key] = this.listQuery[key] == null ? '' : this.listQuery[key]
      }
      delete data.currentPage
      delete data.pageSize
      data.startTime =
        data.startTime !== ''
          ? this.listQuery.startTime.getTime()
          : data.startTime
      data.endTime =
        data.endTime !== '' ? this.listQuery.endTime.getTime() : data.endTime
      window.location.href =
        process.env.VUE_APP_BASE_API +
        '/jbl-order/api/merchant/v1/order/export?' +
        urlEncode(data).slice(1)
    },
    // 查看团员
    handleCheckGroupList(row){
      const activityId = row.activityId
      groupMembers({activityId}).then(response=>{
        if(response.code === '200'){
            this.groupDialog = true
            this.totalData = response.data
            this.groupData = response.data.filter(item=>{
              return item.isLeader === 1
            })
        }
      })
    },
    closeGroupCheck(){
      this.groupDialog = false
      this.groupData = []
    },
    handleGroup(row){
      this.membersDialog = true
      this.membersData = this.totalData.filter(item=>{
        return item.groupId === row.groupId
      })
      this.memberLength = this.membersData.length - 1
    },
    closeMemberCheck(){
      this.membersDialog = false
      this.membersData = []
    }
  }
}
</script>
<style lang="scss" scoped>
  .search-form{
    margin-bottom: 20px;
    display: flex;
    flex-wrap: wrap;
    line-height: 40px;
    align-items:center;
    .el-input{
      margin-right: 10px;
    }
  }
</style>
